<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title>智慧大棚系统 - 大棚种类</title>
		<script src="https://cdn.tailwindcss.com"></script>
		<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
		<script src="https://cdn.jsdelivr.net/npm/vue@3.3.11/dist/vue.global.prod.min.js"></script>
		<script src="https://cdn.jsdelivr.net/npm/axios@1.7.7/dist/axios.min.js"></script>

		<!-- Tailwind配置 -->
		<script>
			tailwind.config = {
				theme: {
					extend: {
						colors: {
							primary: '#2E7D32', // 主色调：绿色，代表农业、生长
							secondary: '#1976D2', // 辅助色：蓝色，代表科技、数据
							accent: '#F59E0B', // 强调色：橙色，代表警告、提醒
							neutral: {
								100: '#F9FAFB',
								200: '#F3F4F6',
								300: '#E5E7EB',
								400: '#D1D5DB',
								500: '#9CA3AF',
								600: '#6B7280',
								700: '#4B5563',
								800: '#1F2937',
								900: '#111827'
							}
						},
						fontFamily: {
							inter: ['Inter', 'sans-serif'],
						},
						boxShadow: {
							'card': '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)',
							'card-hover': '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)',
						}
					},
				}
			}
		</script>

		<style type="text/tailwindcss">
			@layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .bg-grid {
                background-image: linear-gradient(#e5e7eb 1px, transparent 1px),
                                  linear-gradient(to right, #e5e7eb 1px, transparent 1px);
                background-size: 20px 20px;
            }
            .errmsg {
                @apply text-red-500 text-xs ml-2;
            }
            .management-title {
                @apply text-xl font-bold text-neutral-800 mb-4 border-b border-neutral-200 pb-2;
            }
            .management-title-dialog {
                @apply text-lg font-bold text-neutral-800 mb-4 border-b border-neutral-200 pb-2;
            }
            .search-container {
                @apply flex flex-wrap gap-2 mb-4;
            }
            .search-input {
                @apply px-3 py-2 border border-neutral-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-200;
            }
            .search-button {
                @apply px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors duration-200;
            }
            .leftmargin {
                @apply ml-2;
            }
            .button-spacing {
                @apply mb-4;
            }
            .button {
                @apply px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors duration-200;
            }
            .editButton {
                @apply bg-blue-600 hover:bg-blue-700;
            }
            .deleteButton {
                @apply bg-red-600 hover:bg-red-700;
            }
            table {
                @apply w-full border-collapse;
            }
            th {
                @apply px-4 py-2 bg-neutral-100 text-left text-xs font-medium text-neutral-600 uppercase tracking-wider border border-neutral-200;
            }
            td {
                @apply px-4 py-2 border border-neutral-200;
            }
            tr:nth-child(even) {
                @apply bg-neutral-50;
            }
            tr:hover {
                @apply bg-neutral-100 transition-colors duration-150;
            }
            .pagination {
                @apply flex mt-4 space-x-2;
            }
            .pagination button {
                @apply px-3 py-1 border border-neutral-300 rounded hover:bg-neutral-100 transition-colors duration-150;
            }
            dialog {
                @apply fixed inset-0 m-auto w-1/2 max-w-md p-6 rounded-lg shadow-xl z-50 bg-white border-none;
            }
            dialog::backdrop {
                @apply bg-black/50 backdrop-blur-sm;
            }
            dialog form {
                @apply space-y-4;
            }
            dialog label {
                @apply block text-sm font-medium text-neutral-700 mb-1;
            }
            dialog input, dialog select, dialog textarea {
                @apply w-full px-3 py-2 border border-neutral-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-200;
            }
            dialog textarea {
                @apply h-24 resize-none;
            }
            .sidebar {
                @apply w-64 bg-white border-r border-neutral-200 h-screen fixed left-0 top-0 pt-20 overflow-y-auto;
            }
            .sidebar ul {
                @apply space-y-1 px-2;
            }
            .sidebar li {
                @apply rounded-md;
            }
            .sidebar a {
                @apply block px-4 py-2 text-neutral-700 hover:bg-primary/10 hover:text-primary rounded-md transition-colors duration-200;
            }
            .sidebar a.active {
                @apply bg-primary/10 text-primary font-medium;
            }
            .header {
                @apply bg-white shadow-md fixed w-full z-50 h-20 flex items-center px-6;
            }
            .header h1 {
                @apply text-xl font-bold text-neutral-800 ml-2;
            }
            .content {
                @apply ml-64 pt-20 px-6 pb-10;
            }
            .greenhouse-card {
                @apply p-3 bg-neutral-50 rounded-lg border border-neutral-200;
            }
            .greenhouse-name {
                @apply font-semibold text-primary mb-1;
            }
            .greenhouse-info {
                @apply text-sm text-neutral-600 mb-1;
            }
            .greenhouse-time {
                @apply text-xs text-neutral-500;
            }
        }
    </style>
	</head>

	<body>
		<div id="app">
			<div class="header">
				<!-- 加入 logo -->
				<div class="bg-primary text-white p-2 rounded-lg">
					<i class="fa-solid fa-farm text-xl"></i>
				</div>
				<h1>智慧大棚管理系统</h1>
			</div>

			<div class="container">
				<!-- 左侧导航栏 -->
				<div class="sidebar">
					<ul>
						<li><a href="/greenhouse/GreenHouseType/list.html" class="sidebar-item">大棚种类管理</a></li>
						<li><a href="/greenhouse/GreenHouseLocation/list.html" class="sidebar-item">大棚位置管理</a></li>
						<li><a href="/greenhouse/GreenHouse/list.html" class="sidebar-item">大棚管理</a></li>
						<li><a href="/greenhouse/Crops/list.html" class="sidebar-item">农产品管理</a></li>
						<li><a href="/greenhouse/PlanType/list.html" class="sidebar-item">计划分类管理</a></li>
						<li><a href="/greenhouse/Plan/list.html" class="sidebar-item">计划管理</a></li>
						<li><a href="/greenhouse/InputType/list.html" class="sidebar-item">投入类别管理</a></li>
						<li><a href="/greenhouse/Input/list.html" class="sidebar-item">投入管理</a></li>
						<li><a href="/greenhouse/Order/list.html" class="sidebar-item">订单管理</a></li>
						<li><a href="/greenhouse/Employee/list.html" class="sidebar-item">员工管理</a></li>
					</ul>
				</div>

				<!-- 内容区域 -->
				<div class="content">
					<h2 class="management-title">大棚种类</h2>

					<div class="search-container">
						<input type="text" class="search-input" placeholder="输入类型名称" v-model="queryParam.typeName">
						<button class="search-button leftmargin" @click="query(1)">查询</button>
					</div>

					<div class="button-spacing">
						<button class="button" @click="openAddDialog">添加大棚类型</button>
					</div>

					<table>
						<thead>
							<tr>
								<th>序号</th>
								<th>大棚种类</th>
								<th>操作</th>
							</tr>
						</thead>
						<tbody>
							<tr v-for="(item, index) in page.records" :key="item.id">
								<td>{{index + 1}}</td>
								<td>
									<div class="greenhouse-card">
										<div class="greenhouse-name">{{item.typeName}}</div>
										<div class="greenhouse-info">适宜作物: {{item.suitableCrops}}</div>
										<div class="greenhouse-info">结构特点: {{item.structureFeatures}}</div>
										<div class="greenhouse-time">创建时间: {{item.createTime}}</div>
									</div>
								</td>
								<td>
									<button class="button editButton" @click="openEditDialog(item.id)">编辑</button>
									<button class="button deleteButton"
										@click="openDeleteConfirmDialog(item.id)">删除</button>
								</td>
							</tr>
						</tbody>
					</table>

					<!-- 分页组件 -->
					<div class="pagination">
						<button @click="query(1)">首页</button>
						<button @click="query(page.pageNum - 1)" :disabled="page.pageNum === 1">上一页</button>
						<button v-for="index in page.pages" @click="query(index)">{{index}}</button>
						<button @click="query(page.pageNum + 1)" :disabled="page.pageNum === page.pages">下一页</button>
						<button @click="query(page.pages)" :disabled="page.pageNum === page.pages">末页</button>
					</div>
				</div>
			</div>

			<!-- 添加数据的对话框 -->
			<dialog ref="addDialogRef">
				<h2 class="management-title-dialog">添加大棚类型</h2>
				<form>
					<label>类型名称：</label>
					<input type="text" placeholder="输入类型名称" v-model="addParam.typeName">
					<span class="errmsg" v-show="errShow.typeName">请输入类型名称</span>

					<label>适宜作物：</label>
					<input type="text" placeholder="输入适宜作物" v-model="addParam.suitableCrops">
					<span class="errmsg" v-show="errShow.suitableCrops">请输入适宜作物</span>

					<label>结构特点：</label>
					<textarea placeholder="输入结构特点" v-model="addParam.structureFeatures"></textarea>
					<span class="errmsg" v-show="errShow.structureFeatures">请输入结构特点</span>

					<div class="flex justify-end space-x-2">
						<button class="button" type="button" @click="add">保存</button>
						<button class="button bg-neutral-600" type="button" @click="closeAddDialog">取消</button>
					</div>
					<span class="errmsg" v-show="errShow.addError">添加失败,请重新输入或者联系管理员</span>
				</form>
			</dialog>

			<!-- 编辑数据的对话框 -->
			<dialog ref="editDialogRef">
				<h2 class="management-title-dialog">编辑大棚类型</h2>
				<form>
					<label>类型名称：</label>
					<input type="text" placeholder="输入类型名称" v-model="updateParam.typeName">
					<span class="errmsg" v-show="errShow.typeName">请输入类型名称</span>

					<label>适宜作物：</label>
					<input type="text" placeholder="输入适宜作物" v-model="updateParam.suitableCrops">
					<span class="errmsg" v-show="errShow.suitableCrops">请输入适宜作物</span>

					<label>结构特点：</label>
					<textarea placeholder="输入结构特点" v-model="updateParam.structureFeatures"></textarea>
					<span class="errmsg" v-show="errShow.structureFeatures">请输入结构特点</span>

					<div class="flex justify-end space-x-2">
						<button class="button" type="button" @click="update">保存</button>
						<button class="button bg-neutral-600" type="button" @click="closeEditDialog">取消</button>
					</div>
					<span class="errmsg" v-show="errShow.updateError">更新失败,请重新输入或者联系管理员</span>
				</form>
			</dialog>

			<!-- 删除确认对话框 -->
			<dialog ref="confirmDialogRef">
				<p>您确定删除吗？</p>
				<div class="flex justify-end space-x-2">
					<button class="button" @click="confirmDelete">确定</button>
					<button class="button bg-neutral-600" @click="closeDeleteConfirmDialog">取消</button>
				</div>
			</dialog>
		</div>

		<script>
			const {
				createApp,
				ref,
				reactive,
				onMounted
			} = Vue;

			createApp({
				setup() {
					// 查询参数
					const queryParam = reactive({
						typeName: '',
						pageNum: 1,
						pageSize: 10
					});

					// 分页结果
					const page = reactive({
						records: [],
						total: 0,
						pages: 1,
						pageNum: 1,
						pageSize: 10
					});

					// 添加参数
					const addParam = reactive({
						typeName: '',
						suitableCrops: '',
						structureFeatures: ''
					});

					// 更新参数
					const updateParam = reactive({
						id: null,
						typeName: '',
						suitableCrops: '',
						structureFeatures: '',
						createTime: ''
					});

					// 错误提示
					const errShow = reactive({
						typeName: false,
						suitableCrops: false,
						structureFeatures: false,
						addError: false,
						updateError: false,
						queryError: false
					});

					// 对话框引用
					const addDialogRef = ref(null);
					const editDialogRef = ref(null);
					const confirmDialogRef = ref(null);

					// 当前操作的ID
					const currentId = ref(null);

					// 加载状态
					const loading = ref(false);

					// 格式化日期
					const formatDate = (date) => {
						const d = new Date(date);
						return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
					};

					// 生命周期钩子 - 页面加载完成后执行
					onMounted(() => {
						// 初始化加载数据
						query(1);
					});

					// 查询数据
					const query = async (pageNum) => {
						queryParam.pageNum = pageNum;
						loading.value = true;

						try {
							// 模拟API调用
							await new Promise(resolve => setTimeout(resolve, 500));

							// 模拟返回数据
							let mockData = [{
									id: 1,
									typeName: '日光温室',
									suitableCrops: '西红柿,黄瓜,辣椒',
									structureFeatures: '单坡面结构,北墙保温,采光面朝南',
									createTime: '2023-01-15 09:30'
								},
								{
									id: 2,
									typeName: '连栋温室',
									suitableCrops: '花卉,草莓,叶菜',
									structureFeatures: '多跨连栋结构,空间利用率高,自动化程度高',
									createTime: '2023-02-20 14:15'
								},
								{
									id: 3,
									typeName: '塑料大棚',
									suitableCrops: '早春蔬菜,秋延后蔬菜',
									structureFeatures: '拱形结构,覆盖塑料薄膜,造价低',
									createTime: '2023-03-10 10:45'
								},
								{
									id: 4,
									typeName: '玻璃温室',
									suitableCrops: '高档花卉,育苗',
									structureFeatures: '钢架结构,玻璃覆盖,透光性好,使用寿命长',
									createTime: '2023-04-05 11:20'
								},
								{
									id: 5,
									typeName: '生态温室',
									suitableCrops: '有机蔬菜,食用菌',
									structureFeatures: '生态循环系统,节能环保,多功能',
									createTime: '2023-05-12 16:30'
								},
								{
									id: 6,
									typeName: '智能温室',
									suitableCrops: '高附加值作物,实验品种',
									structureFeatures: '物联网控制系统,环境自动调节,数据监测',
									createTime: '2023-06-18 13:10'
								},
								{
									id: 7,
									typeName: '简易大棚',
									suitableCrops: '季节性蔬菜',
									structureFeatures: '竹木结构,造价低廉,搭建方便',
									createTime: '2023-07-22 08:45'
								},
								{
									id: 8,
									typeName: '双层膜温室',
									suitableCrops: '越冬蔬菜',
									structureFeatures: '双层塑料薄膜,保温性能好',
									createTime: '2023-08-30 15:20'
								},
								{
									id: 9,
									typeName: '光伏温室',
									suitableCrops: '耐阴作物',
									structureFeatures: '顶部安装光伏板,发电与种植结合',
									createTime: '2023-09-14 10:10'
								},
								{
									id: 10,
									typeName: '实验温室',
									suitableCrops: '科研品种',
									structureFeatures: '分区控制,环境可调,数据采集系统',
									createTime: '2023-10-25 14:50'
								}
							];

							// 应用过滤条件 - 模糊查询
							if (queryParam.typeName) {
								mockData = mockData.filter(item =>
									item.typeName.toLowerCase().includes(queryParam.typeName.toLowerCase())
								);
							}

							// 计算分页数据
							const startIndex = (pageNum - 1) * queryParam.pageSize;
							const endIndex = startIndex + queryParam.pageSize;

							page.records = mockData.slice(startIndex, endIndex);
							page.total = mockData.length;
							page.pages = Math.ceil(page.total / queryParam.pageSize);
							page.pageNum = pageNum;

							errShow.queryError = false;
						} catch (error) {
							console.error('查询失败:', error);
							errShow.queryError = true;
						} finally {
							loading.value = false;
						}
					};

					// 打开添加对话框
					const openAddDialog = () => {
						// 重置添加参数
						Object.assign(addParam, {
							typeName: '',
							suitableCrops: '',
							structureFeatures: ''
						});

						// 重置错误提示
						resetErrorShow();

						// 显示对话框
						addDialogRef.value.showModal();
					};

					// 关闭添加对话框
					const closeAddDialog = () => {
						addDialogRef.value.close();
					};

					// 添加大棚类型
					const add = async () => {
						// 表单验证
						if (!validateAddForm()) {
							return;
						}

						loading.value = true;

						try {
							// 模拟API调用
							await new Promise(resolve => setTimeout(resolve, 500));

							// 模拟添加成功后刷新数据
							const newId = Math.max(...page.records.map(item => item.id)) + 1;
							const newItem = {
								id: newId,
								typeName: addParam.typeName,
								suitableCrops: addParam.suitableCrops,
								structureFeatures: addParam.structureFeatures,
								createTime: formatDate(new Date())
							};

							// 在实际项目中应该使用axios调用后端API
							// const response = await axios.post('/api/greenhouse-types', addParam);
							// const newItem = response.data;

							// 添加到列表
							page.records.unshift(newItem);
							page.total++;
							page.pages = Math.ceil(page.total / queryParam.pageSize);

							closeAddDialog();
							alert('添加成功');
						} catch (error) {
							console.error('添加失败:', error);
							errShow.addError = true;
						} finally {
							loading.value = false;
						}
					};

					// 打开编辑对话框
					const openEditDialog = async (id) => {
						loading.value = true;
						currentId.value = id;

						try {
							// 模拟API调用获取数据
							await new Promise(resolve => setTimeout(resolve, 300));

							// 找到要编辑的数据
							const item = page.records.find(item => item.id === id);

							if (item) {
								// 填充编辑表单
								Object.assign(updateParam, {
									id: item.id,
									typeName: item.typeName,
									suitableCrops: item.suitableCrops,
									structureFeatures: item.structureFeatures,
									createTime: item.createTime
								});

								// 重置错误提示
								resetErrorShow();

								// 显示对话框
								editDialogRef.value.showModal();
							}
						} catch (error) {
							console.error('获取数据失败:', error);
						} finally {
							loading.value = false;
						}
					};

					// 关闭编辑对话框
					const closeEditDialog = () => {
						editDialogRef.value.close();
					};

					// 更新大棚类型
					const update = async () => {
						// 表单验证
						if (!validateUpdateForm()) {
							return;
						}

						loading.value = true;

						try {
							// 模拟API调用
							await new Promise(resolve => setTimeout(resolve, 500));

							// 找到要更新的记录索引
							const index = page.records.findIndex(item => item.id === updateParam.id);

							if (index !== -1) {
								// 更新记录
								page.records[index].typeName = updateParam.typeName;
								page.records[index].suitableCrops = updateParam.suitableCrops;
								page.records[index].structureFeatures = updateParam.structureFeatures;

								// 显示成功消息
								alert('大棚类型信息已更新');

								// 关闭对话框
								closeEditDialog();
							} else {
								errShow.updateError = true;
							}
						} catch (error) {
							console.error('更新失败:', error);
							errShow.updateError = true;
						} finally {
							loading.value = false;
						}
					};

					// 打开删除确认对话框
					const openDeleteConfirmDialog = (id) => {
						currentId.value = id;
						confirmDialogRef.value.showModal();
					};

					// 关闭删除确认对话框
					const closeDeleteConfirmDialog = () => {
						confirmDialogRef.value.close();
					};

					// 确认删除
					const confirmDelete = async () => {
						loading.value = true;

						try {
							// 模拟API调用
							await new Promise(resolve => setTimeout(resolve, 500));

							// 模拟删除成功
							page.records = page.records.filter(item => item.id !== currentId.value);
							page.total--;
							page.pages = Math.ceil(page.total / queryParam.pageSize);

							// 如果当前页没有数据了，跳转到上一页
							if (page.records.length === 0 && page.pageNum > 1) {
								query(page.pageNum - 1);
							}

							closeDeleteConfirmDialog();
							alert('删除成功');
						} catch (error) {
							console.error('删除失败:', error);
						} finally {
							loading.value = false;
						}
					};

					// 验证添加表单
					const validateAddForm = () => {
						let isValid = true;

						resetErrorShow();

						if (!addParam.typeName) {
							errShow.typeName = true;
							isValid = false;
						}

						if (!addParam.suitableCrops) {
							errShow.suitableCrops = true;
							isValid = false;
						}

						if (!addParam.structureFeatures) {
							errShow.structureFeatures = true;
							isValid = false;
						}

						return isValid;
					};

					// 验证更新表单
					const validateUpdateForm = () => {
						let isValid = true;

						resetErrorShow();

						if (!updateParam.typeName) {
							errShow.typeName = true;
							isValid = false;
						}

						if (!updateParam.suitableCrops) {
							errShow.suitableCrops = true;
							isValid = false;
						}

						if (!updateParam.structureFeatures) {
							errShow.structureFeatures = true;
							isValid = false;
						}

						return isValid;
					};

					// 重置错误提示
					const resetErrorShow = () => {
						Object.assign(errShow, {
							typeName: false,
							suitableCrops: false,
							structureFeatures: false,
							addError: false,
							updateError: false,
							queryError: false
						});
					};

					return {
						queryParam,
						page,
						addParam,
						updateParam,
						errShow,
						addDialogRef,
						editDialogRef,
						confirmDialogRef,
						query,
						openAddDialog,
						closeAddDialog,
						add,
						openEditDialog,
						closeEditDialog,
						update,
						openDeleteConfirmDialog,
						closeDeleteConfirmDialog,
						confirmDelete,
						loading
					};
				}
			}).mount('#app');
		</script>
	</body>

</html>